package smarthouse.ejb;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import smarthouse.conv.Conversions;
import smarthouse.dto.PrivilegeDTO;
import smarthouse.model.Privilege;

/**
 * Session Bean implementation class PrivilegeDAO
 */
@Stateless
@Local
public class PrivilegeDAO implements PrivilegeDAORemote {

	@EJB
	Conversions conv;

	@PersistenceContext
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public PrivilegeDAO() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public PrivilegeDTO getPrivilegebyId(int id) {
		TypedQuery<Privilege> usersReturn = em.createNamedQuery(
				"Privilege.findAll", Privilege.class);

		List<Privilege> users = usersReturn.getResultList();
		for (Privilege u : users) {
			if (u.getUserId() == id) {
				return conv.privilege_C_2_DTO(u);
			}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean updatePrivilege(PrivilegeDTO user) {
		Privilege u = em.find(Privilege.class, user.getUserId());
		u.setHouseLook(user.isHouseLook());
		u.setLights(user.isLights());
		u.setRoomEl(user.isRoomEl());
		u.setTemp(user.isTemp());
		em.merge(u);
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean addPrivilege(PrivilegeDTO priv) {
		Privilege u = em.find(Privilege.class, priv.getUserId());

		if (u == null) {
			em.persist(conv.privilege_DTO_2_C(priv));
			return true;
		} else {
			em.merge(conv.privilege_DTO_2_C(priv));
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean removePrivilege(int id) {
		Privilege u = em.find(Privilege.class, id);

		if (u == null) {
			return false;
		} else {
			em.remove(u);
			return true;
		}

	}
}
